<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="单据编号" prop="docNum">
        <el-input
          v-model="queryParams.docNum"
          placeholder="请输入单据编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据时间">
        <el-date-picker
          v-model="daterangeDocDt"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:transfer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:transfer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:transfer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:transfer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transferList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期时间" align="center" prop="docDt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.docDt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据编号" align="center" prop="docNum" width="180" />
      <el-table-column label="调出仓库" align="center" prop="stockNameFrom"/>

      <el-table-column label="调入仓库" align="center" prop="stockNameTo"/>


      <el-table-column label="经办人" align="center" prop="attentionUserNickName" />
      <el-table-column label="审核人" align="center" prop="confirmUserNickName" />
      <el-table-column label="审核时间" align="center" prop="confirmDt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.confirmDt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="oaDictConfirmStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_dict_confirm_status" :value="scope.row.oaDictConfirmStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:transfer:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:transfer:remove']"
            :disabled="scope.row.oaDictConfirmStatus !='editing'">删除</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="showDialog_confirm(scope.row)"
            v-hasPermi="['wms:transfer:remove']"
            :disabled="scope.row.oaDictConfirmStatus !='waiting'">审核</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改调拨单对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="95px">
        <el-alert v-show="form.oaDictConfirmStatus != 'editing'"
                  style="margin-bottom: 15px;"
                  :title="form.latestTaskInfo"
                  type="info"
                  :closable="false"
                  effect="dark"
        >
        </el-alert>
        <el-row>
          <el-col :span="12">

            <el-form-item label="单据编号" prop="docNum">
              <el-input v-model="form.docNum" placeholder="请输入单据编号" />
            </el-form-item>


            <el-form-item label="调出仓库" prop="dictWarehouseFrom">
              <el-input v-model="form.dictWarehouseFrom" v-show="false"/>
              <el-input placeholder="请点击右侧按钮选择仓库" readOnly="true" v-model="form.selectedStockFrom" class="input-with-select"
                        :style="{width: '100%'}">
                <el-button type="info" plain
                           @click="dialog_show_stock_from"
                           slot="append" icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-form-item>

            <el-form-item label="经办人" prop="fkAttentionUserId">
              <el-input v-model="form.fkAttentionUserId" v-show="false"/>
              <el-input placeholder="请选择经办人" v-model="form.selectedAttentionUser" class="input-with-select">
                <el-button @click="showDialog_selAttentionUser(form)" :style="{width: '100%'}"
                           slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>

          </el-col>

          <el-col :span="12">

            <el-form-item label="单据时间" prop="docDt">
              <el-date-picker clearable size="small" style="width: 100%"
                              v-model="form.docDt"
                              type="datetime"
                              format="yyyy-MM-dd HH:mm"
                              value-format="yyyy-MM-dd HH:mm:00"
                              placeholder="选择单据时间">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="调入仓库" prop="dictWarehouseTo">
              <el-input v-model="form.dictWarehouseTo" v-show="false"/>
              <el-input placeholder="请点击右侧按钮选择仓库" readOnly="true" v-model="form.selectedStockTo" class="input-with-select"
                        :style="{width: '100%'}">
                <el-button type="info" plain
                           @click="dialog_show_stock_to"
                           slot="append" icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-form-item>

          </el-col>

        </el-row>

        <el-row>

          <el-form-item label="备注" prop="docNote">
            <el-input v-model="form.docNote" type="textarea" placeholder="请输入内容" />
          </el-form-item>

        </el-row>

        <el-divider content-position="center">调拨单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWmsTransferDetail" :disabled="form.oaDictConfirmStatus != 'editing'">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWmsTransferDetail" :disabled="form.oaDictConfirmStatus != 'editing'">删除</el-button>
          </el-col>
        </el-row>

        <el-table :data="wmsTransferDetailList" :row-class-name="rowWmsTransferDetailIndex" @selection-change="handleWmsTransferDetailSelectionChange" ref="wmsTransferDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>

          <el-table-column label="物料名称" prop="itemName" width="240px" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fkItemUuid" v-show="false"/>
              <el-input placeholder="请选择物料" readOnly="true" v-model="scope.row.itemName"
                        class="input-with-select">
                <el-button @click="showDialog_selItem(scope)" slot="append" icon="el-icon-search"
                ></el-button>
              </el-input>
            </template>
          </el-table-column>

            <el-table-column label="计量单位" align="center" prop="wmsDictMeasuringUnit" width="100">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.wmsDictMeasuringUnit"/>
              </template>
            </el-table-column>
          <el-table-column label="调拨数量" prop="transQty" width="120" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.transQty" placeholder="请输入调拨数量" />
            </template>
          </el-table-column>

          <el-table-column label="调出仓位" prop="fkStkPosUuidFrom" width="180" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fkStkPosUuidFrom" v-show="false"/>
              <el-input placeholder="请选择仓位名称" readOnly="true" v-model="scope.row.stockPosNameFrom"
                        class="input-with-select">
                <el-button @click="dialog_show_stockPosition_from(scope)" slot="append" icon="el-icon-search"
                ></el-button>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column label="调入仓位" prop="fkStkPosUuidTo" width="180" align="center">
            <template slot-scope="scope">

              <el-input v-model="scope.row.fkStkPosUuidTo" v-show="false"/>
              <el-input placeholder="请选择仓位名称" readOnly="true" v-model="scope.row.stockPosNameTo"
                        class="input-with-select">
                <el-button @click="dialog_show_stockPosition_to(scope)" slot="append" icon="el-icon-search"
                ></el-button>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column label="备注" prop="docNote" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.docNote" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.oaDictConfirmStatus != 'editing'">确 定</el-button>
        <el-button type="warning" @click="submitForm('waiting')" :disabled="form.oaDictConfirmStatus != 'editing'">提交待审</el-button>

          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <select-user ref="comp_selAttentionUser" @ok="selAttentionUser_done"/>
    <select-item ref="comp_selItem" @ok="selItem_done"/>
    <confirm ref="component_confirm" :confirmParams="confirmParams" @ok="confirm_done"/>
    <select-stock ref="component_selectStockFrom" @ok="selectStock_done_from" />
    <select-stock ref="component_selectStockTo" @ok="selectStock_done_to" />
    <select-stockPos ref="component_selectStockPosFrom" @ok="selectStockPosition_done_from" />
    <select-stockPos ref="component_selectStockPosTo" @ok="selectStockPosition_done_to" />


  </div>
</template>

<script>
import { listTransfer, getTransfer, delTransfer, addTransfer, updateTransfer, updInventory } from "@/api/wms/transfer";
import {newDocNum} from "@/api/oa/docNum";
import selectUser from "@/views/comn/userGroup/selectUser";
import selectItem from "@/views/wms/wmsItems/selectItem";
import {listStockPosition} from "@/api/wms/stockPosition";
import confirm from "@/views/oa/confirm";
import selectStock from "../../wms/stock/selectStock";
import selectStockPos from "../../wms/stockPosition/selectStockPosition";

export default {
  name: "Transfer",
  dicts: ['wms_dict_warehouse', 'wms_dict_warehouse', 'sys_normal_disable', 'oa_dict_confirm_status','wms_dict_measuring_unit'],
  components: {selectUser, selectItem, confirm,selectStock,selectStockPos},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWmsTransferDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 调拨单表格数据
      transferList: [],
      // 调拨单明细表格数据
      wmsTransferDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeDocDt: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictWarehouseFrom: null,
        dictWarehouseTo: null,
        sysNormalDisable: null,
        docTitle: null,
        docNum: null,
        docDt: null,
        docNote: null,
        fkAttentionUserId: null,
        fkConfirmUserId: null,
        confirmDt: null,
        oaDictConfirmStatus: null,
        confirmNote: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dictWarehouseFrom: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
        dictWarehouseTo: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
        sysNormalDisable: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        docNum: [
          { required: true, message: "单据编号不能为空", trigger: "blur" }
        ],
        docDt: [
          { required: true, message: "单据时间不能为空", trigger: "blur" }
        ],
        fkAttentionUserId: [
          { required: true, message: "经办人ID不能为空", trigger: "blur" }
        ],
        oaDictConfirmStatus: [
          { required: true, message: "审核状态不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      },

      details_currRowScope: null, // 明细：当前行
      stockPositions:[], // 仓位
      confirmParams: {},
      confirmPassed: null,

    };
  },
  created() {
    this.getList();

    listStockPosition({}).then(response => {
      this.stockPositions = response.rows
    })

  },

  methods: {

    /** 查询调拨单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDocDt && '' != this.daterangeDocDt) {
        this.queryParams.params["beginDocDt"] = this.daterangeDocDt[0];
        this.queryParams.params["endDocDt"] = this.daterangeDocDt[1];
      }
      listTransfer(this.queryParams).then(response => {
        this.transferList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        tranUuid: null,
        dictWarehouseFrom: null,
        dictWarehouseTo: null,
        sysNormalDisable: "0",
        docTitle: null,
        docNum: null,
        docDt: new Date(),
        docNote: null,
        fkAttentionUserId: null,
        fkConfirmUserId: null,
        confirmDt: null,
        oaDictConfirmStatus: "0",
        confirmNote: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.wmsTransferDetailList = [];
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDocDt = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.tranUuid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.oaDictConfirmStatus = 'editing'
      this.title = "添加调拨单";

      newDocNum({preCode: 'DB-', len: 12}).then(response => {
        this.form.docNum = response.msg
      })

    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const tranUuid = row.tranUuid || this.ids
      getTransfer(tranUuid).then(response => {
        this.form = response.data;
        this.wmsTransferDetailList = response.data.wmsTransferDetailList;
        this.form.oaDictConfirmStatus =
          ('editing' == this.form.oaDictConfirmStatus || 'reject' == this.form.oaDictConfirmStatus)
            ? 'editing' : this.form.oaDictConfirmStatus

          this.form.selectedStockFrom = this.form.stockNameFrom
          this.form.selectedStockTo = this.form.stockNameTo
          this.form.selectedAttentionUser = this.form.attentionUserNickName
        if(row.oaDictConfirmStatus!='editing'||row.oaDictConfirmStatus!='reject'||this.oaDictConfirmStatus!='editing'||this.oaDictConfirmStatus!='reject'){
          this.form.latestTaskInfo='💡 该条记录审核状态为'+
            this.selectDictLabel(this.dict.type.oa_dict_confirm_status, row.oaDictConfirmStatus||this.oaDictConfirmStatus)+'状态'+','+'不能修改'
        }
        this.open = true;
        this.title = "修改调拨单";
      });
    },

    /** 提交按钮 */
    submitForm(confirmStatus) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.wmsTransferDetailList = this.wmsTransferDetailList;
          if(confirmStatus=='waiting') this.form.oaDictConfirmStatus = confirmStatus
          if (this.form.tranUuid != null) {
            updateTransfer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTransfer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const tranUuids = row.tranUuid || this.ids;
      this.$modal.confirm('是否确认删除调拨单编号为"' + tranUuids + '"的数据项？').then(function() {
        return delTransfer(tranUuids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

	  /** 调拨单明细序号 */
    rowWmsTransferDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    /** 调拨单明细添加按钮操作 */
    handleAddWmsTransferDetail() {
      let obj = {};
      obj.fkItemUuid = "";
      obj.itemName = "";
      obj.measuringUnitLabel = "";
      obj.fkStkPosUuidFrom = "";
      obj.fkStkPosUuidTo = "";
      obj.dictMeasuringUnit = "";
      obj.transQty = "";
      obj.sysNormalDisable = "";
      obj.docNote = "";
      this.wmsTransferDetailList.push(obj);
    },
    /** 调拨单明细删除按钮操作 */
    handleDeleteWmsTransferDetail() {
      if (this.checkedWmsTransferDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的调拨单明细数据");
      } else {
        const wmsTransferDetailList = this.wmsTransferDetailList;
        const checkedWmsTransferDetail = this.checkedWmsTransferDetail;
        this.wmsTransferDetailList = wmsTransferDetailList.filter(function(item) {
          return checkedWmsTransferDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleWmsTransferDetailSelectionChange(selection) {
      this.checkedWmsTransferDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/transfer/export', {
        ...this.queryParams
      }, `wms_transfer.xlsx`)
    },


    // 组件 - 选择用户

    /** 选择经办人 */
    showDialog_selAttentionUser(form) {
      this.currentForm = form
      this.$refs.comp_selAttentionUser.show();
    },

    /** 选择经办人 - 完成 */
    selAttentionUser_done(user) {
      this.currentForm.fkAttentionUserId = user.userId
      this.currentForm.selectedAttentionUser = user.userNickNameAndId
    },


    // 组件 - 选择物料


    /** 显示对话框：选择物料 */
    showDialog_selItem(scope) {
      this.details_currRowScope = scope
      this.$refs.comp_selItem.dialog_show_selectItem();
    },

    // 完成：选择物料
    selItem_done(item) {
      this.details_currRowScope.row.itemName = item.itemName
      this.details_currRowScope.row.fkItemUuid = item.itemUuid
      this.details_currRowScope.row.measuringUnitLabel = item.measuringUnitLabel
    },

    /** 打开对话框：审核 */
    showDialog_confirm(row) {
      console.log(row)
      this.confirmPassed = row
      let obj = {
        tableName: 'wms_transfer',
        uuidColumn: 'tran_uuid',
        fkUuid: row.tranUuid,
        attentionUserNickName: row.attentionUserNickName,
        oaDictConfirmStatus: row.oaDictConfirmStatus,
        msg: `请审核调拨单, 单据编号:${row.docNum}`
      }
      this.$refs.component_confirm.showDialog_confirm(obj);
    },

    confirm_done() {
      this.getList()
      this.updInventory()
    },

    /* 更新库存 */
    updInventory(){
      const h = this.$createElement;

      this.$notify({
        title: '调拨单号：' + this.confirmPassed.docNum,
        message: h('i', { style: 'color: teal'}, '调拨单审批通过，库存将被更新！')
      });

      updInventory(this.confirmPassed.tranUuid).then(response => {
        console.log(response)
      });

    },
    /** 显示对话框：选择仓库 */
    dialog_show_stock_from(form) {
      this.$refs.component_selectStockFrom.dialog_show_stock();
    },

    /** 完成：选择仓库*/
    selectStock_done_from(stock) {
      console.log(stock)
      this.form.dictWarehouseFrom = stock.stockUuid
      this.form.selectedStockFrom = stock.stockName
    },
/** 显示对话框：选择仓库 */
    dialog_show_stock_to() {
      this.$refs.component_selectStockTo.dialog_show_stock();
    },

    /** 完成：选择仓库*/
    selectStock_done_to(stock) {
      console.log(stock)
      this.form.dictWarehouseTo = stock.stockUuid
      this.form.selectedStockTo = stock.stockName
    },
    dialog_show_stockPosition_from(scope) {
      if(this.form.dictWarehouseFrom===this.form.dictWarehouseTo){
        this.stockInDetails_currRowScope = scope
        this.$refs.component_selectStockPosFrom.stockPosUuid = scope.row.fkStkPosUuidTo ;
        this.$refs.component_selectStockPosFrom.dialog_show_stockPosition();
      }else{
        this.stockInDetails_currRowScope = scope
        this.$refs.component_selectStockPosFrom.dialog_show_stockPosition();
      }
    },

    /** 完成：选择仓位*/
    selectStockPosition_done_from(stock) {
      console.log(stock)
      this.stockInDetails_currRowScope.row.fkStkPosUuidFrom = stock.stockPosUuid
      this.stockInDetails_currRowScope.row.stockPosNameFrom = stock.stockPosName
    },

    dialog_show_stockPosition_to(scope) {
      if(this.form.dictWarehouseFrom===this.form.dictWarehouseTo){
        this.stockInDetails_currRowScope = scope
        console.log(scope.row.fkStkPosUuidFrom)
        this.$refs.component_selectStockPosTo.stockPosUuid = scope.row.fkStkPosUuidFrom ;
        this.$refs.component_selectStockPosTo.dialog_show_stockPosition();
      }else{
        this.stockInDetails_currRowScope = scope
        this.$refs.component_selectStockPosTo.dialog_show_stockPosition();
      }
    },

    /** 完成：选择仓位*/
    selectStockPosition_done_to(stock) {
      console.log(stock)
      this.stockInDetails_currRowScope.row.fkStkPosUuidTo = stock.stockPosUuid
      this.stockInDetails_currRowScope.row.stockPosNameTo = stock.stockPosName
    },


  }
};
</script>
